﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;

namespace Engine.Input.Handling.KeyboardHandling
{
    public class KeyboardHandler : InputHandler
    {
        #region Properties
        private KeyboardState OldState { get; set; }
        private List<KeyInputBinding> KeyBindings { get; set; }
        #endregion // Properties


        #region Constructors
        internal KeyboardHandler()
        {
            OldState = Keyboard.GetState();
            KeyBindings = KeyInputBinding.LoadFromFile();
        }
        #endregion // Constructors


        #region IInputSampler-Implementation
        public override void SampleInput()
        {
            var currentState = Keyboard.GetState(PlayerIndex.One);
            List<Keys> released = OldState.GetPressedKeys().ToList();

            foreach (var k in KeyBindings)
            {
                if (currentState.IsKeyDown(k.Keys))
                {
                    if (OldState.IsKeyUp(k.Keys))
                        k.OnKeyDown(this);
                }
                else
                {
                    if (OldState.IsKeyDown(k.Keys))
                        k.OnKeyUp(this);
                }
            }

            OldState = currentState;
        }
        #endregion // IInputSampler-Implementation

        public override void Detach()
        {
            KeyInputBinding.SaveToFile(this.KeyBindings);
        }
    }
}
